// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package securitycenter

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/v3.0/security" // nolint: staticcheck
	"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
	"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/securitycenter/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
	"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
	"github.com/hashicorp/terraform-provider-azurerm/utils"
)

const (
	computeProvider = "Microsoft.Compute"
	vmType          = "virtualMachines"
)

func resourceServerVulnerabilityAssessmentVirtualMachine() *pluginsdk.Resource {
	return &pluginsdk.Resource{
		Create: resourceServerVulnerabilityAssessmentVirtualMachineCreate,
		Read:   resourceServerVulnerabilityAssessmentVirtualMachineRead,
		Delete: resourceServerVulnerabilityAssessmentVirtualMachineDelete,

		Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
			_, err := parse.VulnerabilityAssessmentVmID(id)
			return err
		}),

		Timeouts: &pluginsdk.ResourceTimeout{
			Create: pluginsdk.DefaultTimeout(5 * time.Minute),
			Read:   pluginsdk.DefaultTimeout(5 * time.Minute),
			Delete: pluginsdk.DefaultTimeout(10 * time.Minute),
		},

		Schema: map[string]*pluginsdk.Schema{
			"virtual_machine_id": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: commonids.ValidateVirtualMachineID,
			},
		},
	}
}

func resourceServerVulnerabilityAssessmentVirtualMachineCreate(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).SecurityCenter.ServerVulnerabilityAssessmentClient
	ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
	defer cancel()

	virtualMachineId, err := commonids.ParseVirtualMachineID(d.Get("virtual_machine_id").(string))
	if err != nil {
		return err
	}
	id := parse.NewVulnerabilityAssessmentVmID(virtualMachineId.SubscriptionId, virtualMachineId.ResourceGroupName, virtualMachineId.VirtualMachineName, "Default")

	vulnerabilityAssessment, err := client.Get(ctx, virtualMachineId.ResourceGroupName, computeProvider, vmType, virtualMachineId.VirtualMachineName)
	if err != nil {
		if !utils.ResponseWasNotFound(vulnerabilityAssessment.Response) {
			return fmt.Errorf("checking for presence of existing Advanced Threat Protection for %s: %+v", *virtualMachineId, err)
		}
	}

	if !utils.ResponseWasNotFound(vulnerabilityAssessment.Response) {
		return tf.ImportAsExistsError("azurerm_security_center_server_vulnerability_assessment_virtual_machine", *vulnerabilityAssessment.ID)
	}

	_, err = client.CreateOrUpdate(ctx, virtualMachineId.ResourceGroupName, computeProvider, vmType, virtualMachineId.VirtualMachineName)
	if err != nil {
		return fmt.Errorf("create Server Vulnerability Assessment for %s: %+v", *virtualMachineId, err)
	}

	timeout, _ := ctx.Deadline()
	stateConf := &pluginsdk.StateChangeConf{
		Pending:      []string{"Pending"},
		Target:       []string{"Succeeded"},
		Refresh:      serverVulnerabilityAssessmentVirtualMachineStateRefreshFunc(ctx, client, id.ResourceGroup, id.VirtualMachineName),
		PollInterval: 10 * time.Second,
		Timeout:      time.Until(timeout),
	}

	if _, err := stateConf.WaitForStateContext(ctx); err != nil {
		return fmt.Errorf("waiting for the completion of the creating/updating of %s: %+v", id, err)
	}

	d.SetId(id.ID())
	return resourceServerVulnerabilityAssessmentVirtualMachineRead(d, meta)
}

func resourceServerVulnerabilityAssessmentVirtualMachineRead(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).SecurityCenter.ServerVulnerabilityAssessmentClient
	ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
	defer cancel()

	id, err := parse.VulnerabilityAssessmentVmID(d.Id())
	if err != nil {
		return err
	}

	virtualMachineId := commonids.NewVirtualMachineID(id.SubscriptionId, id.ResourceGroup, id.VirtualMachineName)
	resp, err := client.Get(ctx, virtualMachineId.ResourceGroupName, computeProvider, vmType, virtualMachineId.VirtualMachineName)
	if err != nil {
		if utils.ResponseWasNotFound(resp.Response) {
			log.Printf("Server Vulnerability Assessment was not found for %s: %+v", virtualMachineId, err)
			d.SetId("")
			return nil
		}

		return fmt.Errorf("retrieving Server Vulnerability Assessment status for %s: %+v", virtualMachineId, err)
	}

	d.SetId(id.ID())
	d.Set("virtual_machine_id", virtualMachineId.ID())

	return nil
}

func resourceServerVulnerabilityAssessmentVirtualMachineDelete(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).SecurityCenter.ServerVulnerabilityAssessmentClient
	ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
	defer cancel()

	id, err := parse.VulnerabilityAssessmentVmID(d.Id())
	if err != nil {
		return err
	}

	future, err := client.Delete(ctx, id.ResourceGroup, computeProvider, vmType, id.VirtualMachineName)
	if err != nil {
		return fmt.Errorf("deleting Server Vulnerability Assessment %s: %v", *id, err)
	}
	if err := future.WaitForCompletionRef(ctx, client.Client); err != nil {
		return fmt.Errorf("waiting for deletion of Server Vulnerability Assessment %s: %v", *id, err)
	}
	return nil
}

func serverVulnerabilityAssessmentVirtualMachineStateRefreshFunc(ctx context.Context, client *security.ServerVulnerabilityAssessmentClient, resourceGroup, name string) pluginsdk.StateRefreshFunc {
	return func() (interface{}, string, error) {
		resp, err := client.Get(ctx, resourceGroup, computeProvider, vmType, name)
		if err != nil {
			if utils.ResponseWasNotFound(resp.Response) {
				return nil, "Pending", nil
			}
			return nil, "Error", err
		}

		return "Succeeded", "Succeeded", nil
	}
}
